<template>
  <div class="custom-tree-container">
    <div class="block">
      <el-tree
        :data="data"
        show-checkbox
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button type="text" size="mini" @click="() => append(data)">
              添加
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => remove(node, data)"
            >
              删除
            </el-button>
          </span>
        </span>
      </el-tree>
    </div>
  </div>
</template>
<script>
let id = 1000;

export default {
  name: "goods_cate",
  data() {
    const data = [
      {
        id: 1,
        level:1,
        label: "新品",
        children: [
          {
            id: 4,
            level:2,
            label: "二级 1-1",
          },
        ],
      },
      {
        id: 2,
        level:1,
        label: "一级 2",
        children: [
          {
            id: 5,
            level:2,
            label: "二级 2-1",
          },
          {
            id: 6,
            level:2,
            label: "二级 2-2",
          },
        ],
      },
      {
        id: 3,
        level:1,
        label: "一级 3",
        children: [
          {
            id: 7,
            level:2,
            label: "二级 3-1",
          },
          {
            id: 8,
            level:2,
            label: "二级 3-2",
          },
        ],
      },
    ];
    return {
      data: JSON.parse(JSON.stringify(data)),
      data: JSON.parse(JSON.stringify(data)),
      goods:[]
    };
  },
  methods: {
    append(data) {
      const newChild = { id: id++, label: "testtest", children: [] };
      if (!data.children) {
        this.$set(data, "children", []);
      }
      data.children.push(newChild);
            this.$http({
        url: "/admin/goods_cate",
        goods:this.goods
      }).then((res) => {
        console.log(res);
      });
    },

    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
    },  
  },
};
</script>
